﻿using log4net;
using Nova_BLL;
using Nova_Common;
using Nova_Common.Extend;
using Nova_MOD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using WMS_Api.App_Start;
using WMS_Api.Areas.MesSystem.Models;
using WMS_Api.Controllers;
using WMS_Api.Models;

namespace WMS_Api.Areas.MesSystem.Controllers
{
    /// <summary>
    /// 领料单
    /// </summary>
    [RoutePrefix("api/MesSystem/MaterialRequisition")]
    public class MaterialRequisitionController : BaseMesApiController
    {
        TBill_DelStorageBll delStorageBll = new TBill_DelStorageBll();
        TDelStorage_ListBll delStorageListBll = new TDelStorage_ListBll();
        TBase_MaterialBll materialBll = new TBase_MaterialBll();
        TCommandsDetailBll cmdDetialBll = new TCommandsDetailBll();
        ILog _logger = log4net.LogManager.GetLogger(typeof(MaterialRequisitionController));

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PushInfo")]
        [ValidateModel]
        [MesWebApiExceptionFilter]
        public MesApiResult PushInfo(MesMaterialRequisitionExtendModel param)
        {
            if (param.IsEmpty())
                return Error("领料单参数不能为空!");
            _logger.InfoFormat("MES 推送领料单信息，参数:{0}", param.ToJson());
            if (param.data.IsEmpty())
                return Error("领料单data参数不能为空!");
            if (param.type == 0)
                return Insert(param.data);
            else if (param.type == 1)
                return Error("领料单没有type=1的更新操作!");  // 领料单没有更新的接口
            else if (param.type == 2)
                return Delete(param.data);
            else
                return Error("参数type只能为(0,2)!");

        }

        private MesApiResult Insert(List<MaterialRequisitionData> matRequisitionList)
        {
            StringBuilder errMsg = new StringBuilder();
            List<string> errStockList = new List<string>();
            if (!matRequisitionList.Any())
                return Error("领料单传递的集合参数为空!");
            foreach (var matRequisition in matRequisitionList)
            {
                MainData mainData = matRequisition.main;
                List<MesMaterialRequisition> detail = matRequisition.details;
                if (mainData.IsEmpty()) return Error("领料单传递的main参数为空!");
                if (!detail.Any()) return Error("领料单传递的detial参数为空!");
                DateTime date = DateExtend.GetTime(mainData.create_time, true);
                List<TDelStorage_List> delStorageList = new List<TDelStorage_List>();
                var delStorageModel = delStorageBll.GetByStockNo(mainData.material_requisition_no);
                if (!delStorageModel.IsEmpty())
                {
                    errMsg.AppendFormat("领料单号:{0}已经存在库中，无法新增!", mainData.material_requisition_no);
                    errStockList.Add(mainData.material_requisition_no);
                    continue;
                }
                TBill_DelStorage delStorageEntity = new TBill_DelStorage();
                delStorageEntity.PID = Guid.NewGuid().ToString().ToUpper();
                delStorageEntity.StockNo = mainData.material_requisition_no;
                delStorageEntity.Small_BillType = "11";
                delStorageEntity.Bill_Status = 0;
                delStorageEntity.Async_Status = 0;
                delStorageEntity.B01 = 1; // 1：代表MES创建
                delStorageEntity.OID = "MES";
                delStorageEntity.CDT = date;
                foreach (var mat in matRequisition.details)
                {
                    var materialModel = materialBll.GetByMatCode(mat.part_no);
                    if (materialModel.IsEmpty())
                    {
                        errMsg.AppendFormat("领料单:{0}中的物料编码:{1}不存在库中，无法新增领料单信息!", matRequisition.main.material_requisition_no, mat.part_no);
                        errStockList.Add(mainData.material_requisition_no);
                        return Error(errMsg.ToString());
                    }
                    TDelStorage_List delStorageListEntity = new TDelStorage_List();
                    delStorageListEntity.StockNo = mainData.material_requisition_no;
                    delStorageListEntity.Mat_Code = mat.part_no;
                    delStorageListEntity.TS01 = string.IsNullOrWhiteSpace(mainData.notice_no) ? "" : mainData.notice_no;
                    delStorageListEntity.Num = mat.qty;
                    delStorageListEntity.S01 = mat.part_spec;
                    delStorageListEntity.CDT = date;
                    delStorageList.Add(delStorageListEntity);
                }
                if(!delStorageEntity.IsEmpty() && delStorageList.Any())
                {
                    bool isInsert = delStorageBll.InsertEntity(delStorageEntity, delStorageList);
                    if (!isInsert)
                        errMsg.AppendFormat("领料单号:{0},新增失败!", mainData.material_requisition_no);
                }
            }
            return errMsg.ToString().IsEmpty() ? Success() : Error(errMsg.ToString(), errStockList.ToArray());
        }

        private MesApiResult Delete(List<MaterialRequisitionData> matRequisitionList)
        {
            StringBuilder errMsg = new StringBuilder();
            List<string> errStockList = new List<string>();
            if (!matRequisitionList.Any())
                return Error("领料单传递的集合参数为空!");
            foreach (var matRequisition in matRequisitionList)
            {
                MainData mainData = matRequisition.main;
                List<MesMaterialRequisition> detail = matRequisition.details;
                if (mainData.IsEmpty()) return Error("领料单传递的main参数为空!");
                if (!detail.Any()) return Error("领料单传递的detial参数为空!");

                var delStorageModel = delStorageBll.GetByStockNo(mainData.material_requisition_no);
                if (delStorageModel.IsEmpty())
                {
                    errMsg.AppendFormat("领料单号:{0}不存在库中，无法删除!", mainData.material_requisition_no);
                    errStockList.Add(mainData.material_requisition_no);
                    continue;
                }
                var delStoragelist = delStorageListBll.GetDelStorageListModel(mainData.material_requisition_no);
                int delCount = delStoragelist.Count(e => e.Act_Num > 0 || e.DETAIL_PID != 0);
                if (delCount > 0)
                {
                    errMsg.AppendFormat("领料单号:{0}中已有物料开始出库，已无法删除!", mainData.material_requisition_no);
                    errStockList.Add(mainData.material_requisition_no);
                    continue;
                }
                bool isDel = delStorageBll.DeleteEntity(mainData.material_requisition_no);
                if (!isDel)
                    errMsg.AppendFormat("领料单号:{0},删除失败!", mainData.material_requisition_no);
            }

            return errMsg.ToString().IsEmpty() ? Success() : Error(errMsg.ToString(), errStockList.ToArray());
        }
    }
}
